// pages/user-list/user-list.js
import {
  UserModel
} from '../../models/user.js';

import {
  Lock
} from '../../models/lock.js';

import {
  Log
} from '../../utils/log.js';

import {
  Token
} from '../../utils/token.js';

const token = new Token();

const log = new Log();

const user = new UserModel();

const lock = new Lock();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
      "tabName": "Ta关注",
      "key": "1"
    }, {
      "tabName": "Ta粉丝",
      "key": "2"
    }],
    loadingHidden: true,
    followPageIndex: 1,
    fansPageIndex: 1,
    followers: [],
    fans: [],
    activeKey: "1",
    followersTotal: 0,
    fansTotal: 0,
    followLoading: {
      "show": false,
      "type": "loading"
    },
    fansLoading: {
      "show": false,
      "type": "loading"
    },
    self: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userId: options.userId,
    })

    token.verify().then(res => {
      if (res) {
        this._loadUserFollow();
        this._loadUserFans();
      }
    });
  },

  /**
   * 加载用户关注
   */
  _loadUserFollow() {
    let that = this;
    user.userFollowers(that.data.userId, that.data.followPageIndex).then(res => {

      // 关闭骨架
      that._closeSkeletonView();

      that.setData({
        followersTotal: res.data.total
      })

      if (res.data.content.length > 0) {
        //数组合并
        that.data.followers.push.apply(that.data.followers, res.data.content);
        that.setData({
          followers: that.data.followers
        });
      }
    })
  },

  /**
   * 加载用户粉丝
   */
  _loadUserFans() {
    let that = this;
    user.userFans(that.data.userId, that.data.fansPageIndex).then(res => {

      // 关闭骨架
      that._closeSkeletonView();

      that.setData({
        fansTotal: res.data.total
      })

      if (res.data.content.length > 0) {
        //数组合并
        that.data.fans.push.apply(that.data.fans, res.data.content);
        that.setData({
          fans: that.data.fans
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.activeKey === '1') {
      if (this.data.followersTotal == this.data.followers.length) {
        // 加载全部
        this._showFollowLoadedAllTip();
      } else {
        this.data.followPageIndex++;
        this._showFollowLoadMoreTip();
        this._loadUserFollow();
      }
    } else {
      if (this.data.fansTotal == this.data.fans.length) {
        // 加载全部
        this._showFansLoadedAllTip();
      } else {
        this.data.fansPageIndex++;
        this._showFansLoadMoreTip();
        this._loadUserFans();
      }
    }
  },

  _showFollowLoadedAllTip() {
    this.setData({
      followLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeFollowLoadedAllTip() {
    this.setData({
      followLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showFollowLoadMoreTip() {
    this.setData({
      followLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeFollowLoadMoreTip() {
    this.setData({
      followLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },
  _showFansLoadedAllTip() {
    this.setData({
      fansLoading: {
        "show": true,
        "type": "end"
      }
    })
  },
  _closeFansLoadedAllTip() {
    this.setData({
      fansLoading: {
        "show": false,
        "type": "end"
      }
    })
  },
  _showFansLoadMoreTip() {
    this.setData({
      fansLoading: {
        "show": true,
        "type": "loading"
      }
    })
  },
  _closeFansLoadMoreTip() {
    this.setData({
      fansLoading: {
        "show": false,
        "type": "loading"
      }
    })
  },

  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  changeTabs(e) {
    let activeKey = e.detail.activeKey;
    this.setData({
      activeKey: activeKey
    })
  },
  onFollow(e) {
    let that = this;
    wx.showLoading({
      title: '加载中...',
    })

    let userId = e.currentTarget.dataset.userId;
    let commonConcern = e.currentTarget.dataset.commonConcern;
    let index = e.currentTarget.dataset.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    user.self(userId).then(res => {

      wx.hideLoading();

      if (res.data) {
        wx.showToast({
          title: '不能关注自己',
          icon: 'none',
          duration: 2000
        });
      } else {
        user.follow(userId, commonConcern).then(followInfo => {

          setTimeout(() => {
            let result = commonConcern ? !followInfo.data : followInfo.data;
            that.data.followers[index].commonConcern = result;
            that.setData({
              followers: that.data.followers
            })

            // 关注成功,上报日志
            if (result) {
              log.logFollow(userId);
            }

          }, 600);

          lock.unlock();
        }).catch(err => {
          console.log(err);
          lock.unlock();
        });
      }
      lock.unlock();
    }).catch(err => {
      lock.unlock();
    });

  },
  onFollowFans(e) {

    let that = this;

    wx.showLoading({
      title: '加载中...',
    })

    let userId = e.currentTarget.dataset.userId;
    let follow = e.currentTarget.dataset.follow;
    let index = e.currentTarget.dataset.index;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    user.self(userId).then(res => {

      wx.hideLoading();

      if (res.data) {
        wx.showToast({
          title: '不能关注自己',
          icon: 'none',
          duration: 2000
        });
      } else {
        user.follow(userId, follow).then(followInfo => {

          setTimeout(() => {
            let result = follow ? !followInfo.data : followInfo.data;
            that.data.fans[index].follow = result;
            that.setData({
              fans: that.data.fans
            })

            // 关注成功,上报日志
            if (result) {
              log.logFollow(userId);
            }

          }, 600);

          lock.unlock();
        }).catch(err => {
          console.log(err);
          lock.unlock();
        });
      }
      lock.unlock();
    }).catch(err => {
      lock.unlock();
    });
  },
  onProfile(e) {
    let userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `../profile/profile?userId=${userId}`,
    })
  }
})